<template>
  <div class="home-container">
    <!-- 页面标题 -->
    <div class="header">
      <h1>🎬 视频解析平台</h1>
      <p class="subtitle">支持抖音、TikTok、哔哩哔哩等主流平台</p>
    </div>

    <!-- 主功能区域 -->
    <el-card class="main-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span>视频链接解析</span>
          <el-tag :type="serviceStatus === 'online' ? 'success' : 'danger'" size="small">
            {{ serviceStatus === 'online' ? '服务在线' : '服务离线' }}
          </el-tag>
        </div>
      </template>

      <!-- 输入表单 -->
      <el-form @submit.prevent="handleSingleParse" label-width="120px">
        <el-form-item label="视频链接">
          <el-input 
            v-model="videoUrl"
            placeholder="请输入视频链接，如：https://www.douyin.com/video/..."
            clearable
            size="large"
            :disabled="loading"
          >
            <template #prepend>
              <el-icon><Link /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item label="平台选择">
          <el-select v-model="selectedPlatform" placeholder="选择平台" size="large" style="width: 200px">
            <el-option label="🤖 自动识别" value="auto" />
            <el-option label="📱 抖音" value="douyin" />
            <el-option label="🌍 TikTok" value="tiktok" />  
            <el-option label="📺 哔哩哔哩" value="bilibili" />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button 
            type="primary" 
            size="large"
            @click="handleSingleParse"
            :loading="loading"
            :disabled="!videoUrl.trim()"
          >
            <el-icon v-if="!loading"><VideoPlay /></el-icon>
            {{ loading ? '解析中...' : '开始解析' }}
          </el-button>
          
          <el-button 
            size="large" 
            @click="clearForm"
            :disabled="loading"
          >
            清空
          </el-button>

          <el-button 
            type="info" 
            size="large"
            @click="showBatchDialog = true"
            :disabled="loading"
          >
            批量解析
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 解析结果 -->
    <transition name="fade">
      <div v-if="parseResult" class="result-section">
        <VideoResult :video="parseResult" @download="handleDownload" />
      </div>
    </transition>

    <!-- 错误提示 -->
    <transition name="fade">
      <el-alert
        v-if="errorMessage"
        :title="errorMessage"
        type="error"
        show-icon
        closable
        @close="errorMessage = ''"
        style="margin-top: 20px;"
      />
    </transition>

    <!-- 平台支持说明 -->
    <el-card class="info-card" shadow="never">
      <template #header>
        <span>📖 支持的平台</span>
      </template>
      <div class="platform-list">
        <el-tag 
          v-for="platform in supportedPlatforms" 
          :key="platform.code"
          :type="platform.enabled ? 'success' : 'info'"
          size="large"
          class="platform-tag"
        >
          {{ platform.name }}
        </el-tag>
      </div>
      <p class="info-text">
        💡 提示：支持短链接自动展开，粘贴分享链接即可解析
      </p>
    </el-card>

    <!-- 批量解析对话框 -->
    <el-dialog
      v-model="showBatchDialog"
      title="批量视频解析"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form label-width="100px">
        <el-form-item label="视频链接">
          <el-input
            v-model="batchUrls"
            type="textarea"
            :rows="6"
            placeholder="请输入多个视频链接，每行一个&#10;支持的格式：&#10;https://www.douyin.com/video/123&#10;https://www.tiktok.com/@user/video/456&#10;https://www.bilibili.com/video/BV1xx411c7mu"
          />
          <div class="batch-help">
            每行一个链接，最多支持 {{ maxBatchSize }} 个
          </div>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showBatchDialog = false" :disabled="batchLoading">
            取消
          </el-button>
          <el-button 
            type="primary" 
            @click="handleBatchParse"
            :loading="batchLoading"
            :disabled="!batchUrls.trim()"
          >
            {{ batchLoading ? '解析中...' : '开始批量解析' }}
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 批量解析结果 -->
    <el-dialog
      v-model="showBatchResults"
      title="批量解析结果"
      width="80%"
      :close-on-click-modal="false"
    >
      <div class="batch-results">
        <div class="results-summary">
          <el-statistic title="总计" :value="batchResults.length" suffix="个" />
          <el-statistic title="成功" :value="batchSuccessCount" suffix="个" />
          <el-statistic title="失败" :value="batchResults.length - batchSuccessCount" suffix="个" />
        </div>
        
        <el-table :data="batchResults" style="width: 100%" max-height="400">
          <el-table-column prop="url" label="视频链接" width="200" show-overflow-tooltip />
          <el-table-column prop="title" label="标题" show-overflow-tooltip />
          <el-table-column prop="author" label="作者" width="120" />
          <el-table-column prop="platform" label="平台" width="80" />
          <el-table-column label="状态" width="100">
            <template #default="{ row }">
              <el-tag :type="row.error ? 'danger' : 'success'" size="small">
                {{ row.error ? '失败' : '成功' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120">
            <template #default="{ row }">
              <el-button 
                v-if="!row.error" 
                size="small" 
                @click="handleDownload(row)"
              >
                下载
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Link, VideoPlay } from '@element-plus/icons-vue'
import { VideoAPI, detectPlatform, validateUrl } from '@/api/video'
import VideoResult from '@/components/VideoResult.vue'
import type { VideoInfo, PlatformInfo } from '@/types/api'

// 响应式数据
const videoUrl = ref('')
const selectedPlatform = ref('auto')
const loading = ref(false)
const parseResult = ref<VideoInfo | null>(null)
const errorMessage = ref('')
const serviceStatus = ref<'online' | 'offline'>('offline')
const supportedPlatforms = ref<PlatformInfo[]>([])

// 批量解析相关
const showBatchDialog = ref(false)
const showBatchResults = ref(false)
const batchUrls = ref('')
const batchLoading = ref(false)
const batchResults = ref<any[]>([])
const maxBatchSize = ref(10)

// 计算属性
const batchSuccessCount = computed(() => {
  return batchResults.value.filter(result => !result.error).length
})

// 组件挂载时执行
onMounted(async () => {
  await checkServiceStatus()
  await loadSupportedPlatforms()
})

// 检查服务状态
const checkServiceStatus = async () => {
  try {
    await VideoAPI.healthCheck()
    serviceStatus.value = 'online'
  } catch (error) {
    serviceStatus.value = 'offline'
    console.error('服务状态检查失败:', error)
  }
}

// 加载支持的平台
const loadSupportedPlatforms = async () => {
  try {
    supportedPlatforms.value = await VideoAPI.getSupportedPlatforms()
  } catch (error) {
    console.error('获取平台列表失败:', error)
  }
}

// 单个视频解析
const handleSingleParse = async () => {
  if (!videoUrl.value.trim()) {
    ElMessage.warning('请输入视频链接')
    return
  }

  if (!validateUrl(videoUrl.value)) {
    ElMessage.error('请输入有效的视频链接')
    return
  }

  loading.value = true
  errorMessage.value = ''
  parseResult.value = null

  try {
    const platform = selectedPlatform.value === 'auto' 
      ? detectPlatform(videoUrl.value) 
      : selectedPlatform.value

    const result = await VideoAPI.parseVideo({
      url: videoUrl.value,
      platform: platform
    })

    parseResult.value = result
    ElMessage.success('视频解析成功！')
  } catch (error: any) {
    errorMessage.value = error.message || '视频解析失败，请检查链接是否正确'
    ElMessage.error('解析失败')
  } finally {
    loading.value = false
  }
}

// 批量解析
const handleBatchParse = async () => {
  const urls = batchUrls.value
    .split('\n')
    .map(url => url.trim())
    .filter(url => url.length > 0)

  if (urls.length === 0) {
    ElMessage.warning('请输入至少一个视频链接')
    return
  }

  if (urls.length > maxBatchSize.value) {
    ElMessage.error(`批量解析最多支持 ${maxBatchSize.value} 个链接`)
    return
  }

  batchLoading.value = true
  
  try {
    const results = await VideoAPI.parseBatch({ urls })
    batchResults.value = results.map((result, index) => ({
      url: urls[index],
      ...result,
      error: null
    }))
    
    showBatchDialog.value = false
    showBatchResults.value = true
    ElMessage.success(`批量解析完成，成功 ${batchSuccessCount.value} 个`)
  } catch (error: any) {
    ElMessage.error(error.message || '批量解析失败')
  } finally {
    batchLoading.value = false
  }
}

// 下载视频
const handleDownload = (video: VideoInfo) => {
  if (video.download_url) {
    window.open(video.download_url, '_blank')
    ElMessage.success('开始下载视频')
  } else {
    ElMessage.warning('暂无下载链接')
  }
}

// 清空表单
const clearForm = () => {
  videoUrl.value = ''
  selectedPlatform.value = 'auto'
  parseResult.value = null
  errorMessage.value = ''
}
</script>

<style scoped>
.home-container {
  max-width: 1000px;
  margin: 0 auto;
  padding: 20px;
}

.header {
  text-align: center;
  margin-bottom: 30px;
}

.header h1 {
  font-size: 2.5em;
  color: #409eff;
  margin-bottom: 10px;
}

.subtitle {
  font-size: 1.1em;
  color: #666;
}

.main-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.result-section {
  margin-top: 20px;
}

.info-card {
  margin-top: 20px;
}

.platform-list {
  margin-bottom: 15px;
}

.platform-tag {
  margin-right: 10px;
  margin-bottom: 10px;
}

.info-text {
  color: #666;
  margin: 0;
}

.batch-help {
  font-size: 12px;
  color: #999;
  margin-top: 5px;
}

.batch-results {
  margin-top: 20px;
}

.results-summary {
  display: flex;
  justify-content: space-around;
  margin-bottom: 20px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.5s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .home-container {
    padding: 10px;
  }
  
  .header h1 {
    font-size: 2em;
  }
  
  .results-summary {
    flex-direction: column;
    align-items: center;
  }
  
  .results-summary > * {
    margin-bottom: 10px;
  }
}
</style>